<template>
    <div class="page">
        <!-- 滑动列表 -->
        <swipeout v-for="(item,index) in shopList" :key="index" v-if="haveData">
            <swipeout-item transition-mode="follow">
                <div slot="right-menu">
                    <swipeout-button type="warn" background-color="#ff3b2f" @click.native="deleteshop(item,index)">删除</swipeout-button>
                </div>
                <div slot="content" class="container flex flexSpaceB">
                    <check-icon class="mr5" :value.sync="item.selectbox" @click.native.stop="clickIcon(item,true)"></check-icon>
                    <div class="flex row" @click="toNext('categoryDetail',{cateNo:item.productNo})">
                        <img class="w60 h60" :src="item.picUrl" alt="">
                        <div class="flex col ml10 flexJCB w100">
                            <p class="lh16 bold fs14">{{item.productName | sliceString(9)}}</p>
                            <div class="flex row flexSpaceB">
                                <span class="lh20 price bold fs14">￥ {{item.salePrice}}</span>
                                <div class="flex flexSpaceB" style="text-align:center;">
                                    <span class="w20 h20 lh20 fs18 garys" @click.stop="changeNumber(false,item)">-</span>
                                    <span class="w28 h20 lh20 fs14">{{item.buyNumber}}</span>
                                    <span class="w20 h20 lh20 fs18 gary" @click.stop="changeNumber(true,item)">+</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </swipeout-item>
        </swipeout>
        
        <!-- 空购物车显示内容 -->
        <no-content :isShow="showBg"></no-content>
        <discount-goods v-if="showBg" @funCB="getShopData"></discount-goods>
        <div class="h54"></div>
        <!-- 底部购物车按钮 -->
        <bot-check v-if="haveData" :bottom="5" :checkall.sync="checkAll" @clickCB="clickAll" @sureCB="balance">
            <div class="flex row textL mr10 lh16">
                <span class="gary fs14">合计金额: </span>
                <span class="price bold fs14">￥ {{shopPrice}}</span>
            </div>
        </bot-check>
        <!-- 底部导航 -->
        <bot-navigation></bot-navigation>
        <!-- 是否注册弹窗 -->
        <reg-phone :isShow="isRegPhone" @cancel="cancel" @confirm="confirmCB"></reg-phone>
    </div>
</template>
<script>
import mixins from 'mixins';
import { XNumber,Swipeout, SwipeoutItem, SwipeoutButton, Confirm, CheckIcon } from 'vux';
import { MessageBox, Toast } from "mint-ui";
import { shoppingOrders, getShopping, deletShop, Shopset, isRegister } from "request";
export default {
    mixins:[mixins],
    name:'shopCart',
    components:{
        XNumber,Swipeout, SwipeoutItem, SwipeoutButton, Confirm, CheckIcon
    },
    data(){
        return {
            isRegPhone:false,               //是否注册手机号
            checkAll:false,                 //是否是全选
            shopList:[],                    //所有购物车数据保存
            haveData:false,
        }
    },
    computed:{
        imgUrl(){
            return this.$store._modules.root._children.a.state;
        },
        // 计算选中商品的订单总价
        shopPrice(){
            let price = 0;
            this.shopList.forEach(item => {
                item.selectbox && (price += Number(item.buyNumber * item.salePrice) || 0);
            })
            return price;
        }
    },
    created(){
        this.$vux.loading.show({ text: "Loading" });
        isRegister({}).then(res => {
            if (res.data.result == "7012") {
                this.$vux.loading.hide();
                this.isRegPhone = true;         //是否显示绑定电话号码弹窗
            }else{
                this.getShopData();        //获取购物车数据
            }
        }).catch( err=> this.$vux.loading.hide() )
    },
    methods:{
        //注册手机号逻辑
        confirmCB(){
            this.isRegPhone = false;
            this.getShopData();
        },
        // 获购物车数据方法
        getShopData(){
            getShopping({}).then(res => {
                this.$vux.loading.hide();
                if(res.rspCode == '0000' && res.data.code == '0000'){
                    let arrList = res.data.productList;
                    arrList.forEach(item => {
                        item.buyNumber = Number(item.buyNumber);
                        item.selectbox = item.selectbox === 'true';
                        item.picUrl = this.imgUrl + item.picUrl;
                    });
                    this.shopList = arrList;
                    this.showBg = this.shopList.length == 0;
                    this.haveData = this.shopList.length != 0;
                    this.checkAll = this.shopList.every( item => item.selectbox == true);
                }else{
                    res.data.code == '7000' && (this.showBg = true);
                }
            }).catch(err=> this.$vux.loading.hide())
        },
        //删除购物车商品方法
        deleteshop(item,id){
            let self = this;
            let jsonObj = {
                type:'02',
                productNoS:[item.productNo]
            };
            !!item.specId && (jsonObj.specIdList = [item.specId]);
            this.$vux.confirm.show({
                title:'确定删除?',
                onConfirm () {
                    deletShop(jsonObj).then(res=>{
                        let is = res.rspCode == '0000' && res.data.code == '0000';
                        !!is && self.shopList.splice(id,1);
                        self.haveData = self.shopList.length != 0;
                        self.showBg = self.shopList.length == 0;
                        Toast({ message:!!is ? '删除成功' : '删除失败',position:'middle',duration:2000});
                    }).catch(error => console.log(error));
                }
            })
        },
        //点击子项checkbox事件
        clickIcon(sku,type){
            type && (this.checkAll = this.shopList.every(item=> item.selectbox == true ));
            Shopset({
                isAdd:'02',
                productNo: sku.productNo,
                specIds: sku.specId,
                buynum: sku.buyNumber,
                selectBox: `${sku.selectbox}`
            }).then(res => {
                console.log(res)
            }).catch(err=>console.log(err));
        },
        //全选按钮
        clickAll(val){
            this.shopList.forEach(item => {
                item.selectbox != val && (item.selectbox = val,this.clickIcon(item));
                item.selectbox = val;
            });
        },
        //页面结算按钮
        async balance(){
            //goresultpage保存是否有库存
            let tyarr = '',noselctarr = [],shoparr = [],goResultpage = true;
            this.shopList.forEach(item=>{
                item.imgUrl = item.picUrl;
                item.selectbox && (tyarr += item.productType,shoparr.push(item));
                !item.selectbox && noselctarr.push(item);
            });
            this.$store.commit('setno',noselctarr);
            //是否是实物,地址显示 shopType
            let totaljson = {
                shopType: tyarr.indexOf('1') > -1 ? '1' : '3'
            }
            if(shoparr.length == 0){
                Toast({ message:'请先选择商品', position: 'middle', duration:1000});
                return;
            }
            //开始计算运费,所选商品总额
            // console.log(shoparr)
            // return
            this.$vux.loading.show({ text:'loading' });
            await shoppingOrders({ productList: shoparr }).then(res=>{
                this.$vux.loading.hide();
                if(res.rspCode == '0000' && res.data.resultCode == '00'){
                    let orderList = Object.assign({}, res.data);
                    totaljson.shopIntergral = orderList.totalIntegral;
                    totaljson.shopprice = orderList.totalAmount;
                    totaljson.freight = orderList.totalFreight;
                    totaljson.couponList = orderList.couponList.map(item=>{
                        item.haveclick = item.couponNo == res.data.checkedCouponNo
                        return item;
                    })
                    totaljson.a = "orderList.couponList";
                    goResultpage = true;
                }else if(res.rspCode == '1999'){
                    Toast({ message:'结算失败', position: 'middle', duration:1000});
                    this.$router.push({ path: '/'});
                }else{
                    Toast({ message:'结算失败', position: 'middle', duration:1000});
                    goResultpage = false;
                }
            }).catch(err=>{
                console.log(err);
                goResultpage = false;
                this.$vux.loading.hide();
            });
            //是否有库存，计算是否成功，发送选择商品和计算数据
            if (goResultpage) {
                this.$store.commit("addtotal", totaljson);
                this.$store.commit("slectShop", shoparr);
                console.log(shoparr)
                this.$store.commit("setGoodsInfo",shoparr)
                if (shoparr.length < 1) {
                    MessageBox("", "请选择商品");
                } else {
                    this.$store.commit("setno", noselctarr);
                    this.$store.commit("mchtCouponList", totaljson.couponList);
                    this.$router.push({
                        path:"/goodsResult"
                    });
                }
            }
        },
        //改变商品数量
        changeNumber(type,item){
            if(type){
                item.buyNumber++;
                this.clickIcon(item)
            }else{
                item.buyNumber > 1 && (item.buyNumber--,this.clickIcon(item));
            }
        },
        //购物车取消注册
        cancel(){
            this.showBg = true;
            this.$router.go(-1);
        }
    }
}
</script>
<style scoped lang="less">
@import './index.less';
</style>
